<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="700">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="110px"
    >
      <el-form-item label="租户名称" prop="tenantId">
        <el-select
          v-model="formData.tenantId"
          clearable
          filterable
          collapse-tags
          class="!w-200px"
          placeholder="请选择租户名称"
          :disabled="formType === 'update'"
        >
          <el-option
            v-for="item in tenantList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计量企业名称" prop="meteringName">
        <el-input v-model="formData.meteringName" placeholder="请输入计量企业名称" maxlength="50"/>
      </el-form-item>
      <el-form-item label="商户ID" prop="merchantId">
        <el-input v-model="formData.merchantId" placeholder="请输入商户ID" maxlength="100" :disabled="formType === 'update'"/>
      </el-form-item>
      <el-form-item label="商户秘钥" prop="secretKey">
        <el-input v-model="formData.secretKey" placeholder="请输入商户秘钥" maxlength="100" :disabled="formType === 'update'"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" name="SystemPostForm" setup>
import * as RelevancyApi from "@/api/relevancy";

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref
const formData = ref({
  tenantId: undefined,
  tenantName: undefined,
  meteringName: undefined,
  merchantId: undefined,
  secretKey: undefined
})
const formRules = reactive({
  tenantId: [{ required: true, message: '租户名称不能为空', trigger: 'blur' }],
  meteringName: [{ required: true, message: '计量企业名称不能为空', trigger: 'blur' }],
  merchantId: [{ required: true, message: '商户ID不能为空', trigger: 'blur' }],
  secretKey: [{ required: true, message: '商户秘钥不能为空', trigger: 'blur' }],
})

const tenantList = ref()
/** 获取租户数据 */
const getTenantList = async () => {
  const data = await RelevancyApi.getTenantList()
  tenantList.value = data || []
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  getTenantList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RelevancyApi.getRelateEnterInfoById(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (formData.value.tenantId) {
    const selectedTenant = tenantList.value?.find(
      item => item.id === formData.value.tenantId
    )
    formData.value.tenantName = selectedTenant?.name || ''
  }
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await RelevancyApi.createRelevancy(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      await RelevancyApi.updateRelevancy(formData.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    tenantId: undefined,
    tenantName: undefined,
    meteringName: undefined,
    merchantId: undefined,
    secretKey: undefined
  } as any
  formRef.value?.resetFields()
}
</script>
